﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;
using ConsoleService.Cache;
using ConsoleService.Job;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;
using Quartz;

namespace ConsoleService.Services
{
    public class JobServices
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly ICacheService _cache;
        private IScheduler _scheduler;
        public JobServices(ISchedulerFactory schedulerFactory, ICacheService cache)
        {
            this._schedulerFactory = schedulerFactory;
            this._cache = cache;
        }


        public async Task Run()
        {
            //await RunAsync5();
            //await RunAsync();
            await RunAsync2();
            await RunAsync3();
            
            //await RunAsync4();
           
        }


        /// <summary>
        /// 简单任务调度
        /// </summary>
        /// <returns></returns>
        public async Task RunAsync()
        {
            Console.WriteLine("【任务调度执行A作业开始】.....");
            logger.Warn("【任务调度执行A作业开始】.....");

            //创建触发器
            var trigger = TriggerBuilder.Create()
                        .WithSimpleSchedule(x => x.WithIntervalInHours(72).RepeatForever())//间隔2秒 一直执行

                        .WithIdentity("trigger", "group")//多个任务区分分组名
                        .Build();


            //创建任务
            var job = JobBuilder.Create<MyJob>()
                            //.UsingJobData("Key", "Value")//通过Job添加参数值
                            .WithIdentity("job", "group")
                            .Build();

            _scheduler = await _schedulerFactory.GetScheduler();

            //开启调度器
            await _scheduler.Start();

            //将触发器和任务器绑定到调度器中
            await _scheduler.ScheduleJob(job, trigger);
        }


        /// <summary>
        /// 使用Cron表达式
        /// </summary>
        /// <returns></returns>
        public async Task RunAsync2()
        {
            Console.WriteLine("【同步redis数据作业开始】.....");
            logger.Warn("【同步redis数据作业开始】.....");

            //创建触发器
            var trigger = TriggerBuilder.Create()
                //.WithCronSchedule("0 30 10 ? * 2,3,4,5,6,7 *")//　Cron表达式包含7个字段，秒 分 时 月内日期 月 周内日期 年(可选) https://qqe2.com/cron
                .WithCronSchedule("0 0 0 */1 * ?")//每天0点执行一次 https://qqe2.com/cron        
                .WithIdentity("trigger2", "group2")
                        .Build();

            //创建任务
            var job = JobBuilder.Create<MyJob2>()
                                .WithIdentity("job2", "group2")
                                .Build();

            _scheduler = await _schedulerFactory.GetScheduler();

            //开启调度器
            await _scheduler.Start();

            //将触发器和任务器绑定到调度器中
            await _scheduler.ScheduleJob(job, trigger);
        }


        /// <summary>
        /// 使用Cron表达式
        /// </summary>
        /// <returns></returns>
        public async Task RunAsync3()
        {
            Console.WriteLine("【同步油价数据作业开始】.....");
            logger.Warn("【同步油价数据作业开始】.....");

            //创建触发器
            var trigger = TriggerBuilder.Create()
            //.WithCronSchedule("0 0 0 */1 * ?")//每天0点执行一次 https://qqe2.com/cron
             .WithCronSchedule("0 15 8 * * ?")//每天0点执行一次 https://qqe2.com/cron
                .WithIdentity("trigger3", "group3")
                        .Build();

            //创建任务
            var job = JobBuilder.Create<SynchronousDataJob>()
                                .WithIdentity("job3", "group3")
                                .Build();

            _scheduler = await _schedulerFactory.GetScheduler();

            //开启调度器
            await _scheduler.Start();

            //将触发器和任务器绑定到调度器中
            await _scheduler.ScheduleJob(job, trigger);
        }



        /// <summary>
        /// 使用Cron表达式
        /// </summary>
        /// <returns></returns>
        public async Task RunAsync4()
        {
            Console.WriteLine("【爬取公司数据作业开始】.....");
            logger.Warn("【爬取公司数据作业开始】.....");

            //获取更新的公司数据
            var result = _cache.GetRedis().HGetAll<string>("CompanyList");

            var companyList = new List<string>();
            if (result != null)
            {
                companyList = JsonConvert.DeserializeObject<List<string>>(result.Values.ToList()[0]);
            }

            //创建触发器
            var trigger = TriggerBuilder.Create()
            .WithCronSchedule("0 0 0 */1 * ?")//每天0点执行一次 https://qqe2.com/cron
                                              //.WithCronSchedule("0 0 10 * * ?")//每天0点执行一次 https://qqe2.com/cron
                                              //.WithSimpleSchedule(x => x.WithIntervalInMinutes(1).RepeatForever())
           .UsingJobData("companyList", companyList.ToJson())  //通过在Trigger中添加参数值
             .WithIdentity("trigger4", "group4")
                      .Build();

            //创建任务
            var job = JobBuilder.Create<CompanyDataJob>()
                                .WithIdentity("job4", "group4")
                                .Build();

            _scheduler = await _schedulerFactory.GetScheduler();

            //开启调度器
            await _scheduler.Start();

            //将触发器和任务器绑定到调度器中
            await _scheduler.ScheduleJob(job, trigger);
        }


        /// <summary>
        /// 使用Cron表达式
        /// </summary>
        /// <returns></returns>
        public async Task RunAsync5()
        {
            Console.WriteLine("【分页处理更新公司数据作业开始】.....");
            logger.Warn("【分页处理更新公司数据作业开始】.....");

            //创建触发器
            var trigger = TriggerBuilder.Create()
                .WithSimpleSchedule(x => x.WithIntervalInHours(168).RepeatForever())//间隔2秒 一直执行
                                                                                   //.WithCronSchedule("0 0 17 * * ?")//每天0点执行一次 https://qqe2.com/cron
                .WithIdentity("trigger5", "group5")
                        .Build();

            //创建任务
            var job = JobBuilder.Create<UpdateCompanyJob>()
                                .WithIdentity("job5", "group5")
                                .Build();

            _scheduler = await _schedulerFactory.GetScheduler();

            //开启调度器
            await _scheduler.Start();

            //将触发器和任务器绑定到调度器中
            await _scheduler.ScheduleJob(job, trigger);
        }
    }
}
